package com.hay.sms.listener;

import com.hay.sms.config.SmsProperties;
import com.hay.sms.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @title: SmsListener
 * @Author HuangYan
 * @Date: 2020/8/2 18:55
 * @Version 1.0
 */
@Component
public class SmsListener {

    @Autowired
    private SmsUtils smsUtils;  // 注入短信发送工具类

    @Autowired
    private SmsProperties prop;    // 注入application中消息的配置参数

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "LEYOU.SMS.QUEUE", durable = "true"),
            exchange = @Exchange(value = "LEYOU.SMS.EXCHANGE", type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
            key = {"leyou.sms.send"}
    ))
    public void listenSms(Map<String, String> msg){
        // 如果监听到的消息中，消息为空，则直接返回
        if (CollectionUtils.isEmpty(msg)){
            return;
        }
        // 获取消息中，需要消息接收者的电话和验证码
        String phone = msg.get("phone");
        String code = msg.get("code");
        // 如果为空，返回
        if (StringUtils.isBlank(phone) && StringUtils.isBlank(code)){
            return;
        }
        // 调用消息发送
        smsUtils.sendMsg(phone, code, prop.getSignName(),prop.getVerifyCodeTemplate());
    }
}
